import xlrd
import os
from openpyxl import Workbook,load_workbook
import urllib3
from tqdm import tqdm

def getShadowByxls(path,sheet):


    workbook = xlrd.open_workbook(path)
    #工作表获取 必须对应于表的name
    sheet = workbook.sheet_by_name(sheet)
    #影像映射关系
    shadow_tuple_array = []
    for row_index in range(sheet.nrows):
        #7是影像编号所在列
        shadow_id_value = sheet.cell_value(row_index,7)
        if row_index == 0:
            continue
        if shadow_id_value != '':
            #获取当前坑所在FID
            shadow_id_value.replace(" ","")

            shadow_array_temp=shadow_id_value.split("\n")

            shadow_fid = int(sheet.cell_value(row_index,0))
            #元组 （fid，shadow）
            shadow_tuple_array.append((shadow_fid,shadow_array_temp))

    return shadow_tuple_array


# def getDownloadFile(save_path,shadow_array):


#     for tif in shadow_array:
#         print(tif)

#         tif.strip()
#         tif = tif+".tif"

def readXlxs2Dict(shadow_id_url_path):
        #先读取shadow文件里面的数据
    wb = load_workbook(shadow_id_url_path,read_only=True)

    ws = wb.active
    shadow_id_Dict = {}
    flag = True
    for row in ws.rows:
        if flag:
            flag = False
            continue
        row_data = []
        for _,cell in enumerate(row):
            row_data.append(cell.value)
        
        #print(row_data)
        shadow_id_Dict[row_data[0]] = row_data[1]

    return shadow_id_Dict

def dowloadProcess(save_path,url):

    http = urllib3.PoolManager(
        timeout=None,#超时时间
        retries = 3,#重试测试
        cert_reqs = 'CERT_NONE'    #禁用SSL
    )

    try:
        response = http.request('GET',
                                url,
                                preload_content = False
                                )
        
        total_size = int(response.headers.get('content-length', 0))
        # 创建进度条（单位为字节，自动转换为合适的单位）
        progress_bar = tqdm(
            total=total_size,
            unit='B',           # 字节单位
            unit_scale=True,    # 自动缩放单位（KB、MB等）
            unit_divisor=1024,  # 单位换算因子
            desc=f"下载 {os.path.basename(save_path)}"
        )


        if response.status == 200:
            with open(save_path,'wb') as file:
                for chunk in response.stream(8192):
                    if chunk:  # 过滤空块
                        file.write(chunk)
                        progress_bar.update(len(chunk))  # 更新进度条
            print(f"文件下载完成！保存至{save_path}")

        else:
            print(f"文件下载失败！响应码{response.status}")

    finally:
        response.release_conn()   #释放连接



if __name__ == '__main__':

    #影像excel文件位置

    xls_path = "PSR_84.xls"
    sheet_name = "PSR_84"

    shadow_tuple_array = getShadowByxls(xls_path,sheet_name)

    #print(shadow_tuple_array)

    #保存文件夹位置
    save_dir = os.path.join(os.getcwd(),"moondownloadFile") 
    #不存在就创建
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    shadow_id_url_path = "./shadow_id_URL_tif.xlsx"

    shadow_url_dict = readXlxs2Dict(shadow_id_url_path)

    downxlxs_path = "./downlist.xlsx"

    wk = load_workbook(downxlxs_path,read_only=True)
    wb = wk.active

        # 假设想处理 Excel 中的前 100 行（行号 1-100）
    start_row, end_row = 1, 100  # 注意 Excel 行号从 1 开始
    total_rows = end_row - start_row + 1

    # 使用行号生成器并结合 tqdm
    for row in tqdm(
        (wb[row_num] for row_num in range(start_row, end_row + 1)),
        total=total_rows,
        desc="--下载进度--"
    ):
        
        for _,cell in enumerate(row):
            shadowId = cell.value

            try:
                url = shadow_url_dict[shadowId]
            except Exception as e:
                print(f"{shadowId}无法获取下载url")
                continue
            save_pth = save_dir +"/"+ shadowId+"_map_raw.tif" 

            if not os.path.exists(save_pth):
                dowloadProcess(save_pth, url)
            else:
                print(f"文件已存在: {save_pth}")
            

    #工作表获取 必须对应于表的name
    


    # for row in range(sheet.nrows):
    #     shadowId = sheet.cell_value(row,0)
    #     # print(shadowId)

    #     url = shadow_url_dict[shadowId]

    #     print(url)


    # for tuple_shadow in shadow_tuple_array:

    #     getShadow_id_list = tuple_shadow[1]

    #     getShadow_id = getShadow_id.strip()



    




    # base_URL = ""
    # for tuple_tmp in shadow_tuple_array:
    #     #根据fid创建子文件夹
    #     child_dir = os.path.join(save_dir,tuple_tmp[0])
    #     if os.path.exists(child_dir): 
    #         os.makedirs(child_dir)
        
    #     getDownloadFile(child_dir,tuple_tmp[1])







